<template>
  <div>
    <!-- 第一步 - 创建任务 -->
    <div class="task-container">
      <el-form ref="taskForm" :model="taskData" :rules="rules">
      <!-- 任务基本信息 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>任务基本信息</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <!-- 配置项 - 任务名称 -->
            <div class="common-item item-5">
              <label class="condition-label">任务名称</label>
              <el-form-item class="condition-input" prop="name">
                <el-input type="text" :disabled="taskData.done" placeholder="请输入任务名称" v-model="taskData.name" />
              </el-form-item>
            </div>
            <!-- 配置项 - 平台 -->
            <div class="common-item item-5">
              <label class="condition-label">社交平台</label>
              <el-form-item class="condition-input" prop="system">
                <el-select :disabled="taskData.done" v-model="taskData.system" clearable placeholder="请选择平台">
                  <el-option v-for="(item, index) in systems" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 配置项 - 类型 -->
            <!-- <div class="common-item item-3">
              <label class="condition-label">任务类型</label>
              <el-form-item class="condition-input" prop="system">
                <el-select :disabled="taskData.done" v-model="taskData.type" clearable placeholder="请选择类型">
                  <el-option v-for="(item, index) in types" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div> -->
          </div>
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-10">
              <label class="condition-label">任务描述</label>
              <el-form-item class="condition-input" prop="description">
                <el-input :disabled="taskData.done" v-model="taskData.description" maxlength="100" type="textarea" show-word-limit :rows="4" resize="none" placeholder="请输入任务描述" />
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <!-- 隐写参数 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>私钥解密</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-10" :class="{'item-upload': uploadObj.avatarPromptFilePath.showFileList}">
              <el-tooltip content="切换上传方式" placement="top">
                <label class="condition-label condition-label-change" @click="changeUploadType('avatarPromptFilePath', taskData)">私钥解密提示词</label>
              </el-tooltip>
              <el-form-item class="condition-input" prop="avatarPromptFilePath">
                <el-upload
                  v-if="uploadObj.avatarPromptFilePath.isUploadType"
                  class="upload"
                  :disabled="taskData.done"
                  :ref="uploadObj.uploadRef('avatarPromptFilePath')"
                  drag
                  :action="uploadObj.uploadUrl"
                  :limit="1"
                  :show-file-list="uploadObj.avatarPromptFilePath.showFileList"
                  :before-upload="uploadObj.beforeUpload('avatarPromptFilePath')"
                  :on-success="uploadObj.onSuccess('avatarPromptFilePath', taskData, taskForm)"
                  :on-progress="uploadObj.onProgress('avatarPromptFilePath')"
                  :on-error="uploadObj.onError('avatarPromptFilePath')"
                  :on-remove="uploadObj.onRemove('avatarPromptFilePath')"
                >
                  <transition name="upload">
                    <div class="upload-empty" v-if="!taskData.avatarPromptFilePath">
                      <i class="iconfont icon-icon_update upload-icon"></i>
                      <p class="upload-des">拖拽文件至此或点击上传</p>
                    </div>
                    <div class="upload-content" v-else>
                      <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                      <p class="upload-des">{{ uploadObj.avatarPromptFilePath.fileName }}</p>
                    </div>
                  </transition>
                </el-upload>
                <el-input :disabled="taskData.done" v-else type="textarea" @input="clearData('avatarPromptFilePath')" @change="createBlobTxt($event, 'avatarPromptFilePath', taskData, taskForm)" v-model="uploadObj.avatarPromptFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
              </el-form-item>
            </div>
          </div>
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-10" :class="{'item-upload': uploadObj.userAvatarFilePath.showFileList}">
              <label class="condition-label">私钥文件</label>
              <el-form-item class="condition-input" prop="userAvatarFilePath">
                <el-upload
                  class="upload"
                  :disabled="taskData.done"
                  :ref="uploadObj.uploadRef('userAvatarFilePath')"
                  drag
                  :action="uploadObj.uploadUrl"
                  :limit="1"
                  :show-file-list="uploadObj.userAvatarFilePath.showFileList"
                  :before-upload="uploadObj.beforeUpload('userAvatarFilePath')"
                  :on-success="uploadObj.onSuccess('userAvatarFilePath', taskData, taskForm)"
                  :on-progress="uploadObj.onProgress('userAvatarFilePath')"
                  :on-error="uploadObj.onError('userAvatarFilePath')"
                  :on-remove="uploadObj.onRemove('userAvatarFilePath')"
                >
                  <transition name="upload">
                    <div class="upload-empty" v-if="!taskData.userAvatarFilePath">
                      <i class="iconfont icon-icon_update upload-icon"></i>
                      <p class="upload-des">拖拽文件至此或点击上传</p>
                    </div>
                    <div class="upload-content" v-else>
                      <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                      <p class="upload-des">{{ uploadObj.userAvatarFilePath.fileName }}</p>
                    </div>
                  </transition>
                </el-upload>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <!-- 隐写参数 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>隐写参数</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-5">
              <label class="condition-label">参数选择</label>
              <el-form-item class="condition-input" prop="parameter">
                <el-select :disabled="taskData.done" v-model="taskData.parameter" clearable placeholder="请选择参数文件">
                  <el-option v-for="(item, index) in parameters" :key=index :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="common-item item-5">
              <label class="condition-label">任务类型</label>
              <el-form-item class="condition-input" prop="module">
                <el-select @change="moduleChange" disabled v-model="taskData.module" clearable placeholder="请选择类型">
                  <el-option v-for="(item, index) in modules" :key="index" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <!-- 通用布局行 -->
          <!-- <div class="common-row">
            <div class="common-item item-5">
              <label class="condition-label">社交平台选择</label>
              <el-form-item class="condition-input" prop="userPlatformId">
                <el-select 
                  :disabled="platforms.length < 1 || taskData.done"
                  v-model="taskData.userPlatformId" 
                  clearable 
                  placeholder="请选择平台"
                  @change="platformChange"
                >
                  <el-option v-for="(item, index) in platforms" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="common-item item-5">
              <label class="condition-label">社交平台用户选择</label>
              <el-form-item class="condition-input" prop="userID">
                <el-select 
                  :disabled="users.length < 1 || taskData.done"
                  v-model="taskData.userID" 
                  clearable 
                  placeholder="请选择用户"
                  @change="userChange"
                >
                  <el-option v-for="(item, index) in users" :key="index" :label="item.username" :value="item.id"></el-option>
                  <el-select-loading
                    :hasMore="userObj.hasMore"
                    :page="userObj.page"
                    :loading="userObj.loading"
                    @load-more="userObj.loadingMore"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div> -->
          <!-- 通用布局行 -->
          <!-- <el-form-item style="width: 100%" prop="userTag">
            <el-radio-group :disabled="taskData.done" class="common-row" v-model="taskData.userTag">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="data-show">
                    <div class="data-title">
                      <h3>个性化推荐标签</h3>
                    </div>
                    <div class="data-table data-tag-content">
                      <template v-if="personTags.length > 0">
                        <el-radio v-for="(item, index) in personTags" :key="index" :label="item" :value="item">
                        <el-tag class="data-tag" type="primary">{{ item }}</el-tag>
                        </el-radio>
                      </template>
                      <div v-else class="recommend-empty">
                        <i class="iconfont icon-wushuju1 data-empty-icon"></i>
                        <h3 class="data-empty">暂无数据</h3>
                      </div>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="data-show">
                    <div class="data-title">
                      <h3>群组推荐标签</h3>
                    </div>
                    <div class="data-table data-tag-content">
                      <template v-if="groupTags.length > 0">
                        <el-radio v-for="(item, index) in groupTags" :label="item" :value="item" :key="index">
                        <el-tag class="data-tag" type="success">{{ item }}</el-tag>
                        </el-radio>
                      </template>
                      <div v-else class="recommend-empty">
                        <i class="iconfont icon-wushuju1 data-empty-icon"></i>
                        <h3 class="data-empty">暂无数据</h3>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-radio-group>
          </el-form-item> -->
          <div class="common-row">
            <div class="common-item item-10" :class="{'item-upload': uploadObj.promptFilePath.showFileList}">
              <el-tooltip content="切换上传方式" placement="top">
                <label class="condition-label condition-label-change" @click="changeUploadType('promptFilePath', taskData)">提示词</label>
              </el-tooltip>
              <el-form-item class="condition-input" prop="promptFilePath">
                <el-upload
                  v-if="uploadObj.promptFilePath.isUploadType"
                  class="upload"
                  :disabled="taskData.done"
                  :ref="uploadObj.uploadRef('promptFilePath')"
                  drag
                  :action="uploadObj.uploadUrl"
                  :limit="1"
                  :show-file-list="uploadObj.promptFilePath.showFileList"
                  :before-upload="uploadObj.beforeUpload('promptFilePath')"
                  :on-success="uploadObj.onSuccess('promptFilePath', taskData, taskForm)"
                  :on-progress="uploadObj.onProgress('promptFilePath')"
                  :on-error="uploadObj.onError('promptFilePath')"
                  :on-remove="uploadObj.onRemove('promptFilePath')"
                >
                  <transition name="upload">
                    <div class="upload-empty" v-if="!taskData.promptFilePath">
                      <i class="iconfont icon-icon_update upload-icon"></i>
                      <p class="upload-des">拖拽文件至此或点击上传</p>
                    </div>
                    <div class="upload-content" v-else>
                      <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                      <p class="upload-des">{{ uploadObj.promptFilePath.fileName }}</p>
                    </div>
                  </transition>
                </el-upload>
                <el-input :disabled="taskData.done" v-else type="textarea" @input="clearData('promptFilePath')" @change="createBlobTxt($event, 'promptFilePath', taskData, taskForm)" v-model="uploadObj.promptFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
              </el-form-item>
            </div>
          </div>
          <!-- 通用布局行 -->
          <div class="common-row">
            <div class="common-item item-10" :class="{'item-upload': uploadObj.stegoFilePath.showFileList}">
              <!-- <label class="condition-label">载密文件</label> -->
              <el-tooltip content="切换上传方式" placement="top">
                <label class="condition-label condition-label-change" @click="changeUploadType('stegoFilePath', taskData)">载密文件</label>
              </el-tooltip>
              <el-form-item class="condition-input" prop="stegoFilePath">
                <el-upload
                  class="upload"
                  v-if="uploadObj.stegoFilePath.isUploadType"
                  :disabled="taskData.done"
                  :ref="uploadObj.uploadRef('stegoFilePath')"
                  drag
                  :action="uploadObj.uploadUrl"
                  :limit="1"
                  :show-file-list="uploadObj.stegoFilePath.showFileList"
                  :before-upload="uploadObj.beforeUpload('stegoFilePath')"
                  :on-success="uploadObj.onSuccess('stegoFilePath', taskData, taskForm)"
                  :on-progress="uploadObj.onProgress('stegoFilePath')"
                  :on-error="uploadObj.onError('stegoFilePath')"
                  :on-remove="uploadObj.onRemove('stegoFilePath')"
                >
                  <transition name="upload">
                    <div class="upload-empty" v-if="!taskData.stegoFilePath">
                      <i class="iconfont icon-icon_update upload-icon"></i>
                      <p class="upload-des">拖拽文件至此或点击上传</p>
                    </div>
                    <div class="upload-content" v-else>
                      <i class="iconfont icon-daimawenjian-mian upload-icon"></i>
                      <p class="upload-des">{{ uploadObj.stegoFilePath.fileName }}</p>
                    </div>
                  </transition>
                </el-upload>
                <el-input :disabled="taskData.done" v-else type="textarea" @input="clearData('stegoFilePath')" @change="createBlobTxt($event, 'stegoFilePath', taskData, taskForm)" v-model="uploadObj.stegoFilePath.text" show-word-limit :rows="5" resize="none" placeholder="请输入文本" />
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      </el-form>
      <transition name="upload">
        <!-- 按钮部分 -->
        <div class="btn-groups" v-if="!taskData.done">
          <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
          <button type="button" :disabled="taskData.createFlag" class="btn" @click="handleExtract">消息提取</button>
        </div>
        <div v-else>
          <!-- 结果展示 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>提取消息文件</h3>
                  <div class="data-title-actions">
                    <span class="action aniTxtBtn" @click="downloadFile">下载</span>
                  </div>
                </div>
                <div class="data-table data-table-scroll">
                  <el-image class="file-image" v-if="getModuleShow(taskData.extractingMessageFilePath, taskData.module) === '图像'" fit="contain" :src="taskData.messageFile" :preview-src-list="[taskData.messageFile]" />
                  <p class="text-container" v-else-if="getModuleShow(taskData.extractingMessageFilePath, taskData.module) === '文本'">
                    {{ taskData.messageFile }}
                  </p>
                  <div class="audio-container audio-show" v-else>
                    <i class="iconfont icon-swticonyinle audio-icon"></i>
                    <p class="audio-filename">{{ taskData.messageFile }}</p>
                  </div>
                  <!-- <div class="audio-container" v-else>
                    <i class="iconfont icon-swticonyinle audio-icon"></i>
                    <audio class="audio" :src="taskData.messageFile" controls></audio>
                  </div> -->
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>用户私钥</h3>
                </div>
                <div class="data-table data-table-scroll">
                  <p class="text-container">
                    {{ getRes(taskData.avatarStegoText) }}
                  </p>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </transition>
    </div>
  </div>
</template>
<script setup>
import useAppStore from '@/stores/app';
import { ref, computed, watch, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { API } from '@/utils/status.js';
import { ElMessage } from 'element-plus';
import ElSelectLoading from '@/components/common/ElSelectLoading.vue';
import * as uploadApi from '@/api/file';
import * as request from '@/api/steganography';
import * as recommendRequest from '@/api/recommend';
import * as rule from '@/utils/rules';
// 假数据
const systems = API.steganography.systems;
const types = [
  { value: 0, label: '类型1' },
  { value: 1, label: '类型2' }
];
const parameters = API.steCommon.parameters;
const modules = API.steCommon.modules;

const defaultTaskData = {
  done: false,
  createFlag: false,
  name: '',
  description: '',
  system: null,
  type: null,
  userID: null,
  userPlatformId: null,
  userAvatarFilePath: null,
  userTag: null,
  module: '图像',
  parameter: null,
  stegoFilePath: null,
  avatarPromptFilePath: null,
  // 返回的结果
  extractingMessageFilePath: null,
  avatarStegoText: null,
  messageFile: null
};
const defaultUpload = {
  isUploadType: true,
  text: '',
  dom: null,
  showFileList: false,
  fileName: '',
  uploading: false
};

// ============> data <============
const appStore = useAppStore();
const route = useRoute();
const router = useRouter();
const taskForm = ref(null);
// 获取到的平台数据
const platforms = ref([]);
// 获取到的用户数据
const users = ref([]);
const userObj = ref({
  page: 1,
  loading: false,
  hasMore: true,
  loadingMore(e){
    console.log(e);
    userObj.value.loading = true;
    recommendRequest.getUserList({ platformId: taskData.value.userPlatformId, page: e })
      .then(res => {
        console.log(res)
        let result = JSON.parse(res);
        console.log(result)
        userObj.value.loading = false;
        if (result && result.code === 200 && result.data.users && result.data.users.length > 0){
          const userData = result && result.code === 200 && result.data && result.data.users ? result.data.users : [];
          if (e === 1){
            users.value = [];
          }
          users.value.push(...userData);
          userObj.value.hasMore = users.value.length < result.data.total;
          userObj.value.page = e;
        }
      })
      .catch(err => {
        console.log(err);
        userObj.value.loading = false;
      })
  }
});
const personTags = ref([]);
const groupTags = ref([]);
// 创建任务步骤的表单对象
const taskData = ref({
  done: false,
  createFlag: false,
  name: '',
  description: '',
  system: null,
  type: null,
  userID: null,
  userPlatformId: null,
  userAvatarFilePath: null,
  userTag: null,
  module: '图像',
  parameter: null,
  stegoFilePath: null,
  promptFilePath: null,
  avatarPromptFilePath: null,
  // 返回的结果
  extractingMessageFilePath: null,
  avatarStegoText: null,
  messageFile: null
});
const uploadObj = ref({
  uploadUrl: `${import.meta.env.VITE_FILE_BASE_API}${uploadApi.uploadUrl}`,
  uploadRef(key){
    return function (dom){
      if (dom){
        uploadObj.value[key].dom = dom;
      }
    }
  },
  beforeUpload(key){
    return function (file){
      if (uploadObj.value[key].uploading){
        ElMessage.warning('当前有文件正在上传，请稍后重试');
        return false;
      }
      let extension = file.size < API.upload.commonLimit;
      if (!extension) {
        ElMessage.warning(`上传文件超过大小限制，文件须小于${API.upload.commonLimit / (1024 * 1024)}M`)
      }
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (key === 'userAvatarFilePath'){
        extension = fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为jpg/png/jpeg文件!');
        }
      }
      // if (key === 'stegoFilePath' && taskData.value.module === '音频') {
      //   extension = fileType == 'wav' || fileType == 'mp3' ? true : false;
      //   if (!extension){
      //     ElMessage.warning('上传文件须为wav/mp3文件!');
      //   }
      // }
      if (key === 'stegoFilePath' || key === 'avatarPromptFilePath'){
        extension = fileType == 'txt' ? true : false;
        if (!extension){
          ElMessage.warning('上传文件须为txt文件!');
        }
      }
      uploadObj.value[key].fileName = extension ? file.name : '';
      uploadObj.value[key].showFileList = true;
      return extension;
    }
  },
  onSuccess(key, data, form){
    return function (e){
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      if (e.code === API.code.SUCCESS) { 
        ElMessage.success('上传成功');
        data[key] = e.data.path;
      } else {
        let msg = e.msg || e.message || '上传失败，请稍后重试或联系管理员';
        ElMessage({
          type: 'error',
          duration: 1500,
          message: msg
        });
      }
      form.validateField([key])
    }
  },
  onProgress(key){
    return function (e){
      uploadObj.value[key].showFileList = true;
      uploadObj.value[key].uploading = true;
    }
  },
  onError(key){
    return function (e){
      console.log(e)
      let message = e.msg || e.message || '上传失败，请稍后重试或联系管理员'
      ElMessage({
        type: 'error',
        duration: 1500,
        message
      });
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  onRemove(key){
    return function (e){
      uploadObj.value[key].showFileList = false;
      uploadObj.value[key].uploading = false;
      uploadObj.value[key].dom.clearFiles();
      uploadObj.value[key].fileName = '';
    }
  },
  userAvatarFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  avatarPromptFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  promptFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  },
  stegoFilePath: {
    isUploadType: true,
    text: '',
    dom: null,
    showFileList: false,
    fileName: '',
    uploading: false
  }
});
// 表单验证规则
const rules = {
  name: rule.createRequired('任务名称不能为空'),
  // userID: rule.createRequired('请选择社交平台用户'),
  // userPlatformId: rule.createRequired('请选择社交平台'),
  // userTag: rule.createRequired('请选择用户并选择标签'),
  module: rule.createRequired('请选择媒体类型'),
  // promptFilePath: rule.createRequired('请上传提示词'),
  promptFilePath: rule.createTextUpload(uploadObj.value, 'promptFilePath', '提示词不能为空'),
  userAvatarFilePath: rule.createRequired('请上传私钥文件'),
  // stegoFilePath: rule.createRequired('请上传消息文件')
  stegoFilePath: rule.createTextUpload(uploadObj.value, 'stegoFilePath', '消息文件不能为空'),
  avatarPromptFilePath: rule.createTextUpload(uploadObj.value, 'avatarPromptFilePath', '私钥解密提示词不能为空')
};
const getModuleShow = computed(() => {
  return function (url, module){
    let fileType = url.slice(url.lastIndexOf('.') + 1);
      let images = ['jpg', 'jpeg', 'png', 'bmp'],
          audios = ['mp3', 'wav', 'flac'],
          txts = ['txt'],
          moduleType;
      if (txts.includes(fileType)) {
        moduleType = '文本'; 
      } else if (images.includes(fileType)){
        moduleType = '图像';
      } else {
        moduleType = '音频';
      }
      return moduleType;
  }
})
const getRes = computed(() => {
  return function (jsonArr){
    let strRes = '',
        strArr = JSON.parse(jsonArr);
    strArr[0] = `N: ${strArr[0]}`;
    strArr[1] = `d: ${strArr[1]}`;
    strRes = `${strArr[0]}\n\n${strArr[1]}`;
    return strRes;
  }
})

// ============> hooks <============
onActivated(() => {
  // if (platforms.value.length < 1){
  //   getSystems();
  // }
  let { id, isCreate, reenter } = route.query;
  if (reenter || (id !== undefined && id == taskData.value.id)){
    return;
  }
  if (isCreate){
    init();
    return;
  }
  reInit();
});

// ============> methods <============
function init(){
  taskData.value = Object.assign({}, defaultTaskData);
  personTags.value = [];
  groupTags.value = [];
  uploadObj.value.promptFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.stegoFilePath = Object.assign({}, defaultUpload);
  uploadObj.value.avatarPromptFilePath = Object.assign({}, defaultUpload);
}
function reInit(){
  let { id } = route.query;
  init();
  request.getTaskDetailById({id})
    .then(res => {
      let result = res;
      result.infoData = JSON.parse(res.infoData);
      console.log(result);
      taskData.value.id = result.id;
      taskData.value.name = result.name;
      taskData.value.description = result.description;
      taskData.value.createFlag = false;
      taskData.value.system = null;
      taskData.value.type = null;
      taskData.value.userID = result.infoData.userID;
      taskData.value.userPlatformId = +result.infoData.userPlatformId;
      taskData.value.module = result.infoData.module;
      taskData.value.parameter = result.infoData.parameter;
      taskData.value.userAvatarFilePath = result.infoData.userAvatarFilePath;
      taskData.value.userTag = result.infoData.userTag;
      taskData.value.promptFilePath = result.infoData.promptFilePath;
      taskData.value.avatarPromptFilePath = result.infoData.avatarPromptFilePath;
      uploadObj.value.promptFilePath.fileName = 'prompt.txt';
      uploadObj.value.avatarPromptFilePath.fileName = 'avatarPromptFilePath.txt';
      // if (taskData.value.userID && taskData.value.userPlatformId !== null && taskData.value.userPlatformId !== undefined){
      //   userChange(taskData.value.userID);
      // }
      if (result.infoData.extractingMessageFilePath){
        taskData.value.done = true;
        taskData.value.stegoFilePath = result.infoData.stegoFilePath;
        taskData.value.extractingMessageFilePath = result.infoData.extractingMessageFilePath;
        taskData.value.avatarStegoText = result.infoData.avatarStegoText;
        // let messageName = 'stego';
        // switch (result.infoData.module){
        //   case '图像':
        //     messageName += '.png';
        //     break;
        //   case '文本':
        //     messageName += '.txt';
        //     break;
        //   case '音频':
        //     messageName += '.wav';
        //     break;
        // }
        // uploadObj.value.stegoFilePath.fileName = messageName;
        uploadObj.value.stegoFilePath.fileName = 'stego.txt';
        uploadObj.value.userAvatarFilePath.fileName = 'avatar.png';
        uploadApi.download({filePath: result.infoData.extractingMessageFilePath})
          .then(res => {
            let moduleType = getModuleShow.value(taskData.value.extractingMessageFilePath, taskData.value.module);
            if (moduleType === '图像') {
              taskData.value.messageFile = window.URL.createObjectURL(res.data);
            } else if (moduleType === '音频'){
              let origin = taskData.value.extractingMessageFilePath,
                  index;
              if (origin.lastIndexOf('\\') > 0){
                index = origin.lastIndexOf('\\');
              } else if (origin.lastIndexOf('/') > 0){
                index = origin.lastIndexOf('/');
              }
              taskData.value.messageFile = origin.slice(index + 1);
            } else {
              let reader = new FileReader();
              reader.readAsText(res.data, 'UTF-8');
              reader.onload= function(evt){
                taskData.value.messageFile = evt.target.result || ''
              }
            }
            // console.log(res)
            // let reader = new FileReader();
            //   console.log(reader)
            //   reader.readAsText(res.data, 'UTF-8');
            //   reader.onload= function(evt){
            //     taskData.value.messageFile = evt.target.result || ''
            //     console.log(taskData.value.messageFile)
            //   }
          })
      }
    })
}
// 查询平台列表 - 更新systems
function getSystems(){
  recommendRequest.getPlatform()
    .then(res => {
      let result;
      if (res) {
        result = JSON.parse(res);
        platforms.value = result && result.code === 200 && result.data ? result.data : [];
      }
    })
}
// 根据平台拉取用户列表
function getUsers(){
  // todo - 这里要设计使用page分页拉取用户列表
  recommendRequest.getUserList({ platformId: taskData.value.userPlatformId, page: userObj.value.page })
    .then(res => {
      let result = JSON.parse(res);
      console.log(result)
      if (result && result.code === 200){
        users.value =  result.data && result.data.users ? result.data.users : [];
        userObj.value.page = users.value.length > 0 ? 1 : 0;
      }
    })
}
// 选择平台事件
function platformChange(e){
  userObj.value.page = 1;
  userObj.value.loading = false;
  userObj.value.hasMore = true;
  if (typeof e === 'number'){
    taskData.value.userPlatformId = e;
    taskData.value.userID = null;
    users.value = [];
    // todo - 这里的用户列表拉选要改为下拉滚动分页
    getUsers();
  } else {
    taskData.value.userPlatformId = null;
    taskData.value.userID = null;
    taskData.value.userAvatarFilePath = null;
    users.value = [];
    groupTags.value = [];
    personTags.value = [];
    taskData.value.userTag = null;
  }
}
// 用户选择事件
function userChange(e){
  if (e !== undefined){
    recommendRequest.geTagByUser({
      userId: taskData.value.userID,
      platformId: taskData.value.userPlatformId
    })
      .then(res => {
        let result = JSON.parse(res);
        console.log(result);
        if (result && result.code === 200 && result.data && result.data.tags && Array.isArray(result.data.tags)){
          personTags.value = result.data.tags;
        } else {
          let msg = result.msg || result.message || '获取个性化标签失败，请稍后重试或联系管理员';
          ElMessage.error(msg);
        }
      })
      recommendRequest.getTagByGroup({
        userId: taskData.value.userID,
        platformId: taskData.value.userPlatformId
      })
        .then(res => {
          let result = JSON.parse(res);
          console.log(result);
          if (result && result.code === 200 && result.data && result.data.tags && Array.isArray(result.data.tags)){
            groupTags.value = result.data.tags;
          } else {
            let msg = result.msg || result.message || '生成群组标签失败，请稍后重试或联系管理员';
            ElMessage.error(msg);
          }
        })
  } else {
    groupTags.value = [];
    personTags.value = [];
    taskData.value.userTag = null;
  }
}
function changeUploadType(key, data){
  if (data && data.done){
    return;
  }
  uploadObj.value[key].isUploadType = !uploadObj.value[key].isUploadType;
  uploadObj.value[key].text = '';
  uploadObj.value[key].showFileList = false;
  uploadObj.value[key].fileName = '';
  uploadObj.value[key].uploading = false;
  data[key] = null;
}
function moduleChange(e){
  taskData.value.stegoFilePath = null;
  uploadObj.value.stegoFilePath.fileName = '';
  uploadObj.value.stegoFilePath.text = '';
  if (e === '图像'){
    uploadObj.value.stegoFilePath.isUploadType = true;
  }
}
function clearData(key){
  taskData.value[key] = '';
}
// 上传项文本输入事件
function createBlobTxt(e, key, data, form){
  if (!e){
    taskData.value[key] = '';
    ElMessage.success('上传成功');
    return;
  }
  let filename;
  const blob = new Blob([e], { type: 'text/plain' });
  switch (key){
    case 'promptFilePath':
      filename = 'prompt.txt';
      break;
    case 'stegoFilePath':
      filename = 'stego.txt';
      break;
  }
  const txt = new File([blob], filename, { type: 'text/plain' });
  let formData = new FormData();
  formData.append('file', txt);
  uploadApi.upload(formData)
    .then(res => {
      console.log('上传res')
      ElMessage.success('上传成功');
      taskData.value[key] = res.path;
      console.log(taskData.value)
      form.validateField([key])
    })
    .catch(err => {
      console.log(err)
      let msg = err.msg || err.message || '上传失败，请稍后重试或联系管理员';
      ElMessage.error(msg);
      form.validateField([key])
    })
}
// 下载提取消息文件
function downloadFile(){
  uploadApi.download({filePath: taskData.value.extractingMessageFilePath})
  .then(res => {
    let fileUrl = window.URL.createObjectURL(res.data),
        a = document.createElement('a');
        // disposition = res.headers['content-disposition'],
        // filename = disposition.slice(disposition.lastIndexOf('=') + 1);
    let origin = taskData.value.extractingMessageFilePath,
        index;
    if (origin.lastIndexOf('\\') > 0){
      index = origin.lastIndexOf('\\');
    } else if (origin.lastIndexOf('/') > 0){
      index = origin.lastIndexOf('/');
    }
    let filename = origin.slice(index + 1);
    a.href = fileUrl;
    a.download = filename;
    a.click();
    ElMessage.success('下载开始！');
    window.URL.revokeObjectURL(fileUrl);
  })
  .catch(err => {
    let message = err.msg || err.message || err.data.msg || '下载失败，请稍后重试或联系管理员';
    ElMessage.error(message);
  })
}
function handleCancel(){
  router.back()
}
// 隐写提取
function handleExtract(){
  if (taskData.value.createFlag){
    ElMessage.warning('当前正在进行消息提取，请稍后');
    return;
  }
  taskForm.value.validate(valid => {
    if (valid){
      taskData.value.createFlag = true;
      appStore.openLoading('消息提取中...');
      request.applicationTwoExtract({
        name: taskData.value.name,
        moduleType: API.steganography.moduleType.APPTWO,
        taskType: API.steganography.type.EXTRACT,
        description: taskData.value.description,
        infoData: {
          userID: taskData.value.userID,
          module: taskData.value.module,
          parameter: taskData.value.parameter,
          userPlatformId: taskData.value.userPlatformId,
          userAvatarFilePath: taskData.value.userAvatarFilePath,
          userTag: taskData.value.userTag,
          stegoFilePath: taskData.value.stegoFilePath,
          promptFilePath: taskData.value.promptFilePath,
          avatarPromptFilePath: taskData.value.avatarPromptFilePath
        }
      })
        .then(res => {
          console.log(res);
          taskData.value.createFlag = false;
          appStore.closeLoading();
          if (res && res.infoData && res.infoData.extractingMessageFilePath){
            ElMessage.success('消息提取成功!');
            taskData.value.done = true;
            taskData.value.avatarStegoText = res.infoData.avatarStegoText;
            if (res.infoData.extractingMessageFilePath){
              taskData.value.extractingMessageFilePath = res.infoData.extractingMessageFilePath;
              uploadApi.download({filePath: res.infoData.extractingMessageFilePath})
                .then(res => {
                  // console.log(res);
                  // let reader = new FileReader();
                  // reader.readAsText(res.data, 'UTF-8');
                  // reader.onload= function(evt){
                  //   taskData.value.messageFile = evt.target.result || ''
                  // }
                  let moduleType = getModuleShow.value(taskData.value.extractingMessageFilePath, taskData.value.module);
                  if (moduleType === '图像') {
                    taskData.value.messageFile = window.URL.createObjectURL(res.data);
                  } else if (moduleType === '音频'){
                    let origin = taskData.value.extractingMessageFilePath,
                        index;
                    if (origin.lastIndexOf('\\') > 0){
                      index = origin.lastIndexOf('\\');
                    } else if (origin.lastIndexOf('/') > 0){
                      index = origin.lastIndexOf('/');
                    }
                    taskData.value.messageFile = origin.slice(index + 1);
                  } else {
                    let reader = new FileReader();
                    reader.readAsText(res.data, 'UTF-8');
                    reader.onload= function(evt){
                      taskData.value.messageFile = evt.target.result || ''
                    }
                  }
                  // if (taskData.value.module === '图像' || taskData.value.module === '音频') {
                  //   taskData.value.messageFile = window.URL.createObjectURL(res.data);
                  // } else {
                  //   let reader = new FileReader();
                  //   reader.readAsText(res.data, 'UTF-8');
                  //   reader.onload= function(evt){
                  //     taskData.value.messageFile = evt.target.result || ''
                  //     console.log(taskData.value.messageFile)
                  //   }
                  // }
                })
            }
          } else {
            ElMessage.error('消息提取失败，请稍后重试或联系管理员');
          }
        })
        .catch(err => {
          console.log(err);
          taskData.value.createFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('提交信息有误，请核对后提交');
    }
  })
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-5 {
  width: 49%;
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 20px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.item-10-spe {
  width: 100%;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
  &::v-deep .el-form-item__content {
    align-items: center!important;
  }
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    display: flex;
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.item-upload {
  padding-bottom: 50px;
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
}
.condition-label-change {
  cursor: pointer;
}
.condition-label-change:hover {
  color: var(--color-primary);
}
.prompt-container {
  height: 100px;
  overflow-y: auto;
  line-height: 2;
  word-break: keep-all;
  background-color: var(--color-gray-5);
  padding: 10px;
  @include scrollBar;
}
.condition-input {
  .el-checkbox {
    flex: 1;
    border-radius: 4px;
    background-color: var(--color-gray-7);
  }
  .el-checkbox.is-checked {
    
    background-color: var(--color-main);
    &::v-deep .el-checkbox__label {
      color: var(--color-white-10)!important;
    }
  }
  &::v-deep .el-checkbox__input {
    display: none;
  }
  &::v-deep .el-checkbox__label {
    width: 100%;
    display: inline-block;
    text-align: center;
  }
}
.avatar-container {
  width: 100%;
  padding-bottom: 100%;
  background-color: var(--color-gray-5);
  border: 1px solid var(--color-main-border);
  border-radius: 15px;
  position: relative;
  overflow: hidden;
  .inner {
    position: absolute;
    width: 100%;
    height: 100%;
    padding: 15px;
    @include flex-all-center;
    flex-direction: column;
    h6 {
      color: var(--color-main-5);
      font-size: 16px;
      margin: 10px;
      text-align: center;
    }
  }
}
.flex-align {
  display: flex;
  align-items: center;
}
.data-table-scroll {
  max-height: 220px;
  height: auto;
  overflow-y: auto;
  @include scrollBar;
  .file-image {
    width: 100%;
    height: 190px;
    background-color: var(--color-gray-2);
    border: 1px solid var(--color-main-border);
    border-radius: 6px;
  }
}
.audio-container {
  width: 100%;
  height: 190px;
  background-color: var(--color-gray-2);
  border: 1px solid var(--color-main-border);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  @include flex-all-center;
  .audio-icon {
    font-size: 40px;
    font-weight: bolder;
    color: var(--color-main);
  }
  .audio {
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 105%;
    height: 30px;
    transform: translateX(-50%);
  }
}
.audio-show {
  @include flex-all-center;
  flex-direction: column;
}
.el-radio-group {
  width: 100%;
  font-size: inherit;
  .el-row {
    width: 100%;
  }
}
.data-tag-content {
  height: 120px;
  overflow-y: auto;
  @include scrollBar;
}
.data-tag {
  margin: 10px 10px;
  cursor: pointer;
}
.recommend-empty {
  width: 100%;
  height: 100%;
  min-height: 100px;
  background-color: var(--color-gray-5);
  @include flex-all-center;
  // 无数据提示语
  .data-empty {
    color: var(--color-main-5);
    font-size: 16px;
  }
  // 无数据图标
  .data-empty-icon {
    color: var(--color-main-5);
    font-size: 32px;
  }
}
.data-tag-content .el-radio {
  &::v-deep .el-radio__input {
    display: none;
  }
  &.is-checked .el-tag {
    background-color: var(--color-main-1);
    border-color: var(--color-main-2);
    color: var(--color-main);
    height: 25px;
    padding: 0 10px;
    @include shadow;
  }
  & .el-tag {
    transition: all 0.4s;
  }
}
</style>